<template>
  <div class="table-load">
    <el-upload
      class="upload-demo"
      :action="config.actionUrl"
      ref="uploadRef"
      :on-change="handleChange"
      :limit="1"
      :show-file-list="false"
      :auto-upload="false"
      :on-exceed="handleExceed"
    >
      <el-button size="small" type="primary">选择文件</el-button>
      <el-button size="small" type="success" @click="handleClick"
        >再错了，再选一次</el-button
      >
      <template #tip>
        <div class="el-upload__tip">
          请上传 {{ config.message }} , 且只能上传 一个 excel 文件
        </div>
      </template>
    </el-upload>
    <cy-table :tableData="tableData" :propList="config.propList"></cy-table>
    <el-button
      class="upload"
      type="success"
      @click="submitUpload"
      :disabled="btnDisabled"
      >上传到服务器</el-button
    >
  </div>
</template>

<script lang="ts">
import { ElUpload, ElMessage } from 'element-plus'
import { defineComponent, ref, watch } from 'vue'
import { IItemType } from '../types'
import CyTable from './Table.vue'
// import xlsx from 'xlsx'

export default defineComponent({
  props: {
    config: {
      type: Object,
      required: true
    }
  },
  emits: ['next'],
  components: {
    CyTable
  },
  setup(props, { emit }) {
    const uploadRef = ref<InstanceType<typeof ElUpload>>()

    const dialogVisible = ref(false)
    const btnDisabled = ref(true)

    const fileContent = ref()
    const tableData = ref<IItemType[]>([])

    watch(
      () => tableData.value,
      (newValue, oldValue) => {
        btnDisabled.value = !btnDisabled.value
      }
    )

    const handleChange = (file: any) => {
      fileContent.value = file.raw
      const fileType = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (fileContent.value) {
        if (fileType === 'xlsx' || fileType === 'xls') {
          importFile(fileContent.value)
        } else {
          ElMessage({
            type: 'warning',
            message: '附件格式错误，请重新上传！'
          })
        }
      } else {
        ElMessage({
          type: 'warning',
          message: '请上传附件！'
        })
      }
    }

    const importFile = (value: File) => {
      const reader = new FileReader()
      reader.readAsArrayBuffer(value)
      reader.onload = function () {
        const buffer = reader.result
        if (buffer && typeof buffer !== 'string') {
          const bytes = new Uint8Array(buffer)
          let binary = ''
          for (let i = 0; i < bytes.length; i++) {
            binary += String.fromCharCode(bytes[i])
          }
          const XLSX = require('xlsx')
          const wb = XLSX.read(binary, {
            type: 'binary'
          })
          const outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])

          let arr: IItemType[] = []
          outdata.map((item: any) => {
            const obj: IItemType = {}
            for (const key in item) {
              obj.项目集名称 = item[`项目集名称`]
              obj.项目集经理 = item[`项目集经理`]
              obj.项目名称 = item[`项目名称`]
              obj.项目经理 = item[`项目经理`]
              obj.姓名 = item[`姓名`]
              obj.工号 = item[`工号`]
              obj.序号 = item[`序号`]
              obj.专业组 = item[`专业组`]
              obj.专业线 = item[`专业线`]
            }
            arr.push(obj)
          })
          tableData.value = arr.slice(0)
        }
      }
    }

    const submitUpload = () => {
      console.log('submit')

      if (uploadRef.value) {
        uploadRef.value.submit()
        emit('next')
      }
    }

    const handleExceed = () => {
      ElMessage({
        type: 'warning',
        message: '此步骤只能上传一个文件，如需重新上传，请点击旁边的绿色按钮'
      })
    }

    const handleClick = () => {
      tableData.value = []
      if (uploadRef.value) {
        uploadRef.value.clearFiles()
      }
    }
    // const tableColHasContent = (rowIndex: number, colIndex: number) => {
    //   tableData.value.map(item => {
    //     item
    //   })
    // }
    return {
      submitUpload,
      uploadRef,
      dialogVisible,
      handleChange,
      fileContent,
      tableData,
      importFile,
      handleExceed,
      handleClick,
      btnDisabled
    }
  }
})
</script>

<style scoped lang="less">
.table-load {
  min-height: 300px;
  .upload-demo {
    height: 80px;
  }
  .upload {
    margin-top: 20px;
  }
}
</style>
